package com.ygp.dtp.core.reject.factory;

import com.google.common.collect.Maps;
import com.ygp.dtp.common.exception.DtpException;
import com.ygp.dtp.core.reject.RejectedCountableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;

/**
 * @description: 拒绝策略工厂类,主要是生产拒绝策略
 * @motto: 代码源于生活，高于生活艺术
 * @author: zhouhengzhe
 * @date: 2022/8/9 17:10
 * @since 1.0
 **/
@Component
@Slf4j
public class RejectedCountableFactory {
    /**
     * Spring会自动将Strategy接口的实现类注入到这个Map中，key为bean id，value值则为对应的策略实现类
     */
    @Autowired
    private final Map<String, RejectedCountableHandler> commandMap = Maps.newHashMap();

    /**
     * 获取拒绝策略
     *
     * @return
     */
    public RejectedCountableHandler getRejected(String type) {
        return Optional.ofNullable(commandMap.get(type)).orElse(loadTypeIfNonEqual(type));
    }

    /**
     * 加载拒绝策略类(防止小写)
     */
    private RejectedCountableHandler loadTypeIfNonEqual(String type) {
        ServiceLoader<RejectedCountableHandler> loader = ServiceLoader.load(RejectedCountableHandler.class);
        for (RejectedCountableHandler handler : loader) {
            if (handler.type().equalsIgnoreCase(type)) {
                return handler;
            }
        }
        log.error("找不到指定的rejectHandler：{}", type);
        throw new DtpException("找不到指定的rejectHandler：" + type);
    }
}
